package time2

import (
	"context"
	"fmt"
	"time"
)

func longRunningTask(ctx context.Context) {
	select {
	case <-ctx.Done():
		fmt.Println("Task cancelled")
		return
	default:
		// 模拟长时间运行的任务
		time.Sleep(5 * time.Second)
		fmt.Println("Task completed")
	}
}

func Test() {
	// 创建一个只有500毫秒过期的context
	ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
	defer cancel()

	go longRunningTask(ctx)

	// 等待goroutine完成或超时
	time.Sleep(1 * time.Second)
	fmt.Println("Main function completed")
}
